package com.example.apidocserver.infrastructure.util.user;

import com.example.apidocserver.infrastructure.config.security.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;

import java.util.Optional;

/**
 * 用户工具
 *
 * @author xyqlg
 */
public class UserUtil {
    /**
     * 用户是否有创建权限
     *
     * @return 是否有创建权限
     */
    public static boolean createDocumentFlag() {
        return getUserDetails()
                .map(UserDetailsImpl::getDataRoleValList)
                .map(dataRoleValList -> !CollectionUtils.isEmpty(dataRoleValList) && !(dataRoleValList.contains(1) && dataRoleValList.size() == 1))
                .orElse(false);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    public static Optional<UserDetailsImpl> getUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            // 如果认证信息中有用户信息，返回当前用户信息
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            return Optional.of(userDetails);
        }
        return Optional.empty();
    }

    public static boolean createSpaceFlag() {
        return createDocumentFlag();
    }

    public static boolean isTourists() {
        return !createDocumentFlag();
    }
}
